use serde::Deserialize;
use validator::{Validate, ValidationError};

use crate::middleware::{validator::ValidatedJson, jwt::Claims};

#[derive(Debug, Default, Deserialize, Validate)]
pub struct User {
    // 用户名长度范围：[6-16]
    #[validate(length(min = 6, max = 16))]
    pub username: String,
    #[validate(length(min = 8, max = 16))]
    pub password: String,
    #[validate(email)]
    pub email: String,
    #[validate(range(min = 18, max = 60))]
    pub age: u8,
    #[validate(length(min = 10, max = 100), custom = "validate_custom")]
    pub custom: String,
}

pub async fn add_user(_user: ValidatedJson<User>) -> &'static str {
    // 能进入这个方法，表明数据校验通过
    "user add success!"
}

pub async fn default_user(_claims: Claims) -> String {
    format!("{:#?}", User::default())
}

fn validate_custom(custom: &String) -> Result<(), ValidationError> {
    // 自定义数据校验
    if custom.contains("非法词汇") {
        Err(ValidationError::new("输入包含非法词汇！"))
    } else {
        Ok(())
    }
}
